<?php
/**
 * PHP SDK for haodai.com (using OAuth2)
 * 
 * @author duyumi <duyumi.net@gmail.com>
 * @copyright open.weibo.com
 */
/**
 * 好贷 OAuth 认证类(OAuth2)
 *
 * 授权机制说明请大家参考微博开放平台文档：{@link http://open.weibo.com/wiki/Oauth2}
 *
 * @package sae
 * @author Elmer Zhang 
 * @version 1.0
 */
class HaoDaiOAuth {
	/**
	 * @ignore
	 */
	public $client_id;
	/**
	 * @ignore
	 */
	public $client_secret;
	/**
	 * @ignore
	 */
	public $access_token;
	/**
	 * @ignore
	 */
	public $refresh_token;
	/**
	 * Contains the last HTTP status code returned. 
	 *
	 * @ignore
	 */
	public $http_code;
	/**
	 * Contains the last API call.
	 *
	 * @ignore
	 */
	public $url;
	/**
	 * Set up the API root URL.
	 *
	 * @ignore
	 */
	public $host = HD_API_HOST;
	/**
	 * Set up the API Request Source.
	 *
	 * @ignore
	 */
	public $source = "open.haodai";
	/**
	 * Set up the API Request Authentication.
	 *
	 * @ignore
	 */
	public $auth = "oauth2";
	/**
	 * Set up the API Request Authentication.
	 *
	 * @ignore
	 */
	public $union_ref = HD_REF;
	/**
	 * Set up the API Request Union Mark.
	 *
	 * @ignore
	 */
	public $timeout = 30;
	/**
	 * Set connect timeout.
	 *
	 * @ignore
	 */
	public $connecttimeout = 30;
	/**
	 * Verify SSL Cert.
	 *
	 * @ignore
	 */
	public $ssl_verifypeer = FALSE;
	/**
	 * Respons format.
	 *
	 * @ignore
	 */
	public $format = 'json';
	/**
	 * Decode returned json data.
	 *
	 * @ignore
	 */
	public $decode_json = TRUE;
	/**
	 * Contains the last HTTP headers returned.
	 *
	 * @ignore
	 */
	public $http_info;
	/**
	 * Set the useragnet.
	 *
	 * @ignore
	 */
	public $useragent = 'HAODAI OAuth2 v0.1';

	/**
	 * print the debug info
	 *
	 * @ignore
	 */
	public $debug = FALSE;

	/**
	 * boundary of multipart
	 * @ignore
	 */
	public static $boundary = '';

	/**
	 * Set API URLS
	 */
	/**
	 * @ignore
	 */
	function accessTokenURL()    { return HD_API_HOST.'oauth2/access_token/'; }
	/**
	 * @ignore
	 */
	function authorizeURL()    { return HD_API_HOST.'oauth2/authorize/'; }
	/**
	 * construct WeiboOAuth object
	 */
	function __construct($client_id, $client_secret, $access_token = NULL, $refresh_token = NULL, $union_ref = NULL) {
		$this->client_id = $client_id;
		$this->client_secret = $client_secret;
		$this->access_token = $access_token;
		$this->refresh_token = $refresh_token;				$this->union_ref = empty($union_ref) ? HD_REF : $union_ref;
	}

	/**
	 * authorize接口
	 *
	 * 对应API：{@link http://open.weibo.com/wiki/Oauth2/authorize Oauth2/authorize}
	 *
	 * @param string $url 授权后的回调地址,站外应用需与回调地址一致,站内应用需要填写canvas page的地址
	 * @param string $response_type 支持的值包括 code 和token 默认值为code
	 * @param string $state 用于保持请求和回调的状态。在回调时,会在Query Parameter中回传该参数
	 * @param string $display 授权页面类型 可选范围: 
	 *  - default		默认授权页面		
	 *  - mobile		支持html5的手机		
	 *  - popup			弹窗授权页		
	 *  - wap1.2		wap1.2页面		
	 *  - wap2.0		wap2.0页面		
	 *  - js			js-sdk 专用 授权页面是弹窗，返回结果为js-sdk回掉函数		
	 *  - apponweibo	站内应用专用,站内应用不传display参数,并且response_type为token时,默认使用改display.授权后不会返回access_token，只是输出js刷新站内应用父框架
	 * @return array
	 */
	function getAuthorizeURL( $url, $response_type = 'code', $state = NULL, $display = NULL ) {
		$params = array();
		$params['client_id'] = $this->client_id;
		$params['redirect_uri'] = $url;
		$params['response_type'] = $response_type;
		$params['state'] = $state;
		$params['display'] = $display;
		return $this->authorizeURL() . "?" . http_build_query($params);
	}

	/**
	 * access_token接口
	 *
	 * 对应API：{@link http://open.weibo.com/wiki/OAuth2/access_token OAuth2/access_token}
	 *
	 * @param string $type 请求的类型,可以为:code, password, token
	 * @param array $keys 其他参数：
	 *  - 当$type为code时： array('code'=>..., 'redirect_uri'=>...)
	 *  - 当$type为password时： array('username'=>..., 'password'=>...)
	 *  - 当$type为token时： array('refresh_token'=>...)
	 * @return array
	 */
	function getAccessToken( $type = 'code', $keys ) {
		$params = array();
		$params['client_id'] = $this->client_id;
		$params['client_secret'] = $this->client_secret;
		$params['response_type'] = 'token';
		if ( $type === 'token' ) {
			$params['grant_type'] = 'refresh_token';
			$params['refresh_token'] = $keys['refresh_token'];
		} elseif ( $type === 'code' ) {
			$params['grant_type'] = 'authorization_code';
			$params['code'] = $keys['code'];
			$params['redirect_uri'] = $keys['redirect_uri'];
		} elseif ( $type === 'password' ) {
			$params['grant_type'] = 'password';
			$params['username'] = $keys['username'];
			$params['password'] = $keys['password'];
		} else {
			exit("wrong auth type");
		}
		
		$response = $this->oAuthRequest($this->accessTokenURL(), 'POST', $params);
		
		$token = json_decode($response, true);
		if ( is_array($token) && !isset($token['error']) ) {
			$this->access_token = $token['access_token'];
			$this->refresh_token = $token['refresh_token'];
		} else {
			exit("get access token failed." . $token['error']);
		}
		return $token;
	}

	/**
	 * 解析 signed_request
	 *
	 * @param string $signed_request 应用框架在加载iframe时会通过向Canvas URL post的参数signed_request
	 *
	 * @return array
	 */
	function parseSignedRequest($signed_request) {
		list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
		$sig = self::base64decode($encoded_sig) ;
		$data = json_decode(self::base64decode($payload), true);
		if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') return '-1';
		$expected_sig = hash_hmac('sha256', $payload, $this->client_secret, true);
		return ($sig !== $expected_sig)? '-2':$data;
	}

	/**
	 * @ignore
	 */
	function base64decode($str) {
		return base64_decode(strtr($str.str_repeat('=', (4 - strlen($str) % 4)), '-_', '+/'));
	}

	/**
	 * 读取jssdk授权信息，用于和jssdk的同步登录
	 *
	 * @return array 成功返回array('access_token'=>'value', 'refresh_token'=>'value'); 失败返回false
	 */
	function getTokenFromJSSDK() {
		$key = "haodaijs_" . $this->client_id;
		if ( isset($_COOKIE[$key]) && $cookie = $_COOKIE[$key] ) {
			parse_str($cookie, $token);
			if ( isset($token['access_token']) && isset($token['refresh_token']) ) {
				$this->access_token = $token['access_token'];
				$this->refresh_token = $token['refresh_token'];
				return $token;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	/**
	 * 从数组中读取access_token和refresh_token
	 * 常用于从Session或Cookie中读取token，或通过Session/Cookie中是否存有token判断登录状态。
	 *
	 * @param array $arr 存有access_token和secret_token的数组
	 * @return array 成功返回array('access_token'=>'value', 'refresh_token'=>'value'); 失败返回false
	 */
	function getTokenFromArray( $arr ) {
		if (isset($arr['access_token']) && $arr['access_token']) {
			$token = array();
			$this->access_token = $token['access_token'] = $arr['access_token'];
			if (isset($arr['refresh_token']) && $arr['refresh_token']) {
				$this->refresh_token = $token['refresh_token'] = $arr['refresh_token'];
			}

			return $token;
		} else {
			return false;
		}
	}

	/**
	 * GET wrappwer for oAuthRequest.
	 *
	 * @return mixed
	 */
	function get($url, $parameters = array()) {
		$response = $this->oAuthRequest($url, 'GET', $parameters);
		if ($this->format === 'json' && $this->decode_json) {
			return json_decode($response, true);
		}
		return $response;
	}

	/**
	 * POST wreapper for oAuthRequest.
	 *
	 * @return mixed
	 */
	function post($url, $parameters = array(), $multi = false) {
		$response = $this->oAuthRequest($url, 'POST', $parameters, $multi );
		if ($this->format === 'json' && $this->decode_json) {
			return json_decode($response, true);
		}
		return $response;
	}

	/**
	 * DELTE wrapper for oAuthReqeust.
	 *
	 * @return mixed
	 */
	function delete($url, $parameters = array()) {
		$response = $this->oAuthRequest($url, 'DELETE', $parameters);
		if ($this->format === 'json' && $this->decode_json) {
			return json_decode($response, true);
		}
		return $response;
	}

	/**
	 * Format and sign an OAuth / API request
	 *
	 * @return string
	 * @ignore
	 */
	function oAuthRequest($url, $method, $parameters, $multi = false) {

		if (strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0) {
			$url = "{$this->host}{$url}";
	}

	switch ($method) {
		case 'GET':
			$url = $url . '?source='.$this->source.'&auth='.$this->auth.'&ref='.$this->union_ref.'&'. http_build_query($parameters);
			return $this->http($url, 'GET');
		default:
			$headers = array();
			if (!$multi && (is_array($parameters) || is_object($parameters)) ) {
				$body = http_build_query($parameters);
			} else {
				$body = self::build_http_query_multi($parameters);
				$headers[] = "Content-Type: multipart/form-data; boundary=" . self::$boundary;
			}
			$url = $url . '?source='.$this->source.'&auth='.$this->auth.'&ref='.$this->union_ref;
			return $this->http($url, $method, $body, $headers);
	}
	}

	/**
	 * Make an HTTP request
	 *
	 * @return string API results
	 * @ignore
	 */
	function http($url, $method, $postfields = NULL, $headers = array()) {
		$this->http_info = array();
		$ci = curl_init();
		/* Curl settings */
		curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
		curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
		curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
		curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ci, CURLOPT_ENCODING, "");
		curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
		curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, 1);
		curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
		curl_setopt($ci, CURLOPT_HEADER, FALSE);

		switch ($method) {
			case 'POST':
				curl_setopt($ci, CURLOPT_POST, TRUE);
				if (!empty($postfields)) {
					curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
					$this->postdata = $postfields;
				}
				break;
			case 'DELETE':
				curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
				if (!empty($postfields)) {
					$url = "{$url}?{$postfields}";
				}
		}

		if ( isset($this->access_token) && $this->access_token )
			$headers[] = "Authorization: oauth2 ".$this->access_token;

		if ( !empty($this->remote_ip) ) {
			if ( defined('SAE_ACCESSKEY') ) {
				$headers[] = "SaeRemoteIP: " . $this->remote_ip;
			} else {
				$headers[] = "API-RemoteIP: " . $this->remote_ip;
			}
		} else {
			if ( !defined('SAE_ACCESSKEY') ) {
				$headers[] = "API-RemoteIP: " . $_SERVER['REMOTE_ADDR'];
			}
		}
		curl_setopt($ci, CURLOPT_URL, $url );
		curl_setopt($ci, CURLOPT_HTTPHEADER, $headers );
		curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE );

		$response = curl_exec($ci);
		
		$this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
		$this->http_info = array_merge($this->http_info, curl_getinfo($ci));
		$this->url = $url;

		if ($this->debug) {
			echo "=====post data======\r\n";
			var_dump($postfields);

			echo "=====headers======\r\n";
			print_r($headers);

			echo '=====request info====='."\r\n";
			print_r( curl_getinfo($ci) );

			echo '=====response====='."\r\n";
			print_r( $response );
		}
		curl_close ($ci);
		return $response;
	}

	/**
	 * Get the header info to store.
	 *
	 * @return int
	 * @ignore
	 */
	function getHeader($ch, $header) {
		$i = strpos($header, ':');
		if (!empty($i)) {
			$key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
			$value = trim(substr($header, $i + 2));
			$this->http_header[$key] = $value;
		}
		return strlen($header);
	}

	/**
	 * @ignore
	 */
	public static function build_http_query_multi($params) {
		if (!$params) return '';

		uksort($params, 'strcmp');

		$pairs = array();

		self::$boundary = $boundary = uniqid('------------------');
		$MPboundary = '--'.$boundary;
		$endMPboundary = $MPboundary. '--';
		$multipartbody = '';

		foreach ($params as $parameter => $value) {

			if( in_array($parameter, array('pic', 'image')) && $value{0} == '@' ) {
				$url = ltrim( $value, '@' );
				$content = file_get_contents( $url );
				$array = explode( '?', basename( $url ) );
				$filename = $array[0];

				$multipartbody .= $MPboundary . "\r\n";
				$multipartbody .= 'Content-Disposition: form-data; name="' . $parameter . '"; filename="' . $filename . '"'. "\r\n";
				$multipartbody .= "Content-Type: image/unknown\r\n\r\n";
				$multipartbody .= $content. "\r\n";
			} else {
				$multipartbody .= $MPboundary . "\r\n";
				$multipartbody .= 'content-disposition: form-data; name="' . $parameter . "\"\r\n\r\n";
				$multipartbody .= $value."\r\n";
			}

		}

		$multipartbody .= $endMPboundary;
		return $multipartbody;
	}
}


/**
 * 好贷平台操作类V
 *
 * 使用前需要先手工调用haodai.api.class.php <br />
 *
 * @package open.haodai.com
 * @author duyumi
 * @version 1.0
 */
class HaoDaiClient
{
	/**
	 * 构造函数
	 * 
	 * @access public
	 * @param mixed $akey 好贷开放平台应用APP KEY
	 * @param mixed $skey 好贷开放平台应用APP SECRET
	 * @param mixed $access_token OAuth认证返回的token
	 * @param mixed $refresh_token OAuth认证返回的token secret
	 * @return void
	 */
	function __construct( $akey, $skey, $access_token, $refresh_token = NULL, $union_ref='')
	{
		$this->oauth = new HaoDaiOAuth( $akey, $skey, $access_token, $refresh_token, $union_ref);
	}
	
	/**
	 * 开启调试信息
	 *
	 * 开启调试信息后，SDK会将每次请求微博API所发送的POST Data、Headers以及请求信息、返回内容输出出来。
	 *
	 * @access public
	 * @param bool $enable 是否开启调试信息
	 * @return void
	 */
	function set_debug( $enable )
	{
		$this->oauth->debug = $enable;
	}

	/**
	 * 设置用户IP
	 *
	 * SDK默认将会通过$_SERVER['REMOTE_ADDR']获取用户IP，在请求微博API时将用户IP附加到Request Header中。但某些情况下$_SERVER['REMOTE_ADDR']取到的IP并非用户IP，而是一个固定的IP（例如使用SAE的Cron或TaskQueue服务时），此时就有可能会造成该固定IP达到微博API调用频率限额，导致API调用失败。此时可使用本方法设置用户IP，以避免此问题。
	 *
	 * @access public
	 * @param string $ip 用户IP
	 * @return bool IP为非法IP字符串时，返回false，否则返回true
	 */
	function set_remote_ip( $ip )
	{
		if ( ip2long($ip) !== false ) {
			$this->oauth->remote_ip = $ip;
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 获取信贷产品列表
	 *
	 * 对应API：{@link http://api.haodai.com/xindai/get_xindai_list xindai/get_xindai_list}
	 *
	 * @access public
	 * @param string $city 信贷产品所属城市，默认北京
	 * @param string $type_id 信贷产品类别，默认消费类
	 * @param int 	 $money 贷款金额，默认1万
	 * @param int 	 $month 贷款期限，默认12个月
	 * @param int 	 $page 返回结果的页码，默认为1
	 * @param int  	 $page_size 单页返回的记录条数，默认为10
	 * @param array  $data 信贷产品筛选参数数组 [参考 接口 get_xindai_filter]
	 * @return array
	 */
	function get_xindai_list($city='beijing' , $xd_type='xiaofei', $money=1, $month=12, $data=array(), $page=1, $page_size=10 )
	{
		$params = array();
		$params['xd_type'] = $xd_type;
		$params['city'] = $city;
		$params['page'] = $page;
		$params['page_size'] = $page_size;
		$params['money'] = $money;
		$params['month']= $month;
		$params = array_merge($params,$data);
		return $this->oauth->get('xindai/get_xindai_list', $params);
	}
	
	/**
	 * 获取单个信贷产品详情
	 *
	 * 对应API：{@link http://api.haodai.com/xindai/get_xindai_detail xindai/get_xindai_detail}
	 *
	 * @access public
	 * @param string $city 信贷产品所属城
	 * @param int 	 $item_id 信贷产品id
	 * @param int 	 $money 贷款金额，默认1万
	 * @param int 	 $month 贷款期限，默认12个月
	 * @return array
	 */
	function get_xindai_detail($city, $item_id, $money=1, $month=12)
	{
		$params = array();
		$params['item_id'] = $item_id;
		$params['city'] = $city;
		$params['money'] = $money;
		$params['month']= $month;
		return $this->oauth->get('xindai/get_xindai_detail', $params);
	}
	
	/**
	 * 提交信贷产品申请
	 *
	 * <br />对应API：{@link http://api.haodai.com/xindai/send_xindai_apply xindai/send_xindai_apply}
	 *
	 * @access public
	 * @param string $city 信贷产品所属城市
	 * @param string $nickname 申请人昵称
	 * @param int 	 $money 贷款金额，默认1万
	 * @param int 	 $mobile 申请人手机号
	 * @param array  $data 其他上传参数，非必须 [邮箱:email, 产品:xd_id, 产品类型:xd_type, 机构ID:bank_id, 申请期限:month, 问题集合:remark, 补充文字:details]
	 * @return array
	 */
	function send_xindai_apply($city, $nickname, $money, $mobile, $data=array())
	{
		if(empty($city)||empty($nickname)||empty($mobile)||empty($money))
		{
			return false;
		}
		$params = array();
		$params['city'] = $city;
		$params['nickname'] = $nickname;
		$params['mobile'] = $mobile;
		$params['money'] = $money;
		$params = array_merge($data,$params);
		return $this->oauth->post( 'xindai/send_xindai_apply', $params, true );
	}

	/**
	 * 获取信贷产品筛选规则
	 *
	 * 返回所有的信贷产品筛选规则
	 * <br />对应API：{@link http://api.haodai.com/xindai/get_xindai_filter xindai/get_xindai_filter}
	 * 
	 * @access public
	 * @return array
	 */
	function get_xindai_filter($xd_type)
	{
		$params = array();
		$params['xd_type'] = $xd_type;
		return $this->oauth->get( 'xindai/get_xindai_filter', $params );
	}
	
	
	/**
	 * 获取已开通信的贷服务地区
	 *
	 * 返回目前所有已经开放的信贷服务地区
	 * <br />对应API：{@link http://api.haodai.com/xindai/get_xindai_zones xindai/get_xindai_zones}
	 * 
	 * @access public
	 * @return array
	 */
	function get_xindai_zones()
	{
		$params = array();
		return $this->oauth->get( 'xindai/get_xindai_zones', $params );
	}
	
	
	
	/**
	 * 发送信贷产品申请的用户自述
	 *
	 * 信贷产品的申请
	 * 对应API：{@link http://api.haodai.com/xindai/send_xindai_apply_details xindai/send_xindai_apply_details}
	 *
	 * @param int     $id  信贷产品申请的表单id，由信贷产品申请的接口返回
	 * @param string  $details  用户自述的文字
	 * @param int     $xd_type  信贷产品的类型
	 * @return array
	 */
	function send_xindai_apply_details($id, $details, $xd_type=FALSE)
	{
		$params = array();
		$params['id'] = intval($id);
		$params['details'] = $details; 
		$params['xd_type'] = $xd_type;
		return $this->oauth->post('xindai/send_xindai_apply_details', $params);
	}

	/**
	 * 信贷产品快速申请
	 *
	 * 对应API：{@link http://api.haodai.com/xindai/send_xindai_apply_fast xindai/send_xindai_apply_fast}
	 *
	 * @param string $city 信贷产品所属城市
	 * @param string $nickname 申请人昵称
	 * @param int 	 $money 贷款金额，默认1万
	 * @param int 	 $mobile 申请人手机号
	 * @param array  $data 其他上传参数,非必须 [产品:xd_id, 产品类型:xd_type]
	 * @return array
	 */
	function send_xindai_apply_fast( $city, $nickname, $money, $mobile, $data=array())
	{
		$params = array();
		$params['city'] = $city;
		$params['nickname'] = $nickname;
		$params['mobile'] = $mobile;
		$params['money'] = $money;
		$params = array_merge($data,$params);
		return $this->oauth->post('xindai/send_xindai_apply_fast', $params);
	}


	/**
	 * 获取热门贷款推荐。 
	 *
	 * 对应API：{@link http://api.haodai.com/common/get_hot_recommend common/get_hot_recommend}
	 * 
	 * @access public
	 * @param string $city 获取热门贷款推荐所属城市。
	 * @return array
	 */
	function get_hot_recommend( $city )
	{
		$params = array();
		$params['city'] = $city;
		return $this->oauth->get('common/get_hot_recommend', $params);
	}

	/**
	 * 获取信贷产品推荐列表
	 *
	 * 对应API：{@link http://api.haodai.com/xindai/get_xindai_ad xindai/get_xindai_ad}
	 * 
	 * @access public
	 * @param string $city 获取热门贷款推荐所属城市。
	 * @return array
	 */
	function get_xindai_ad( $city )
	{
		$params = array();
		$params['city'] = $city;
		return $this->oauth->get('xindai/get_xindai_ad', $params);
	}

	/**
	 * 获取贷款攻略文章
	 *
	 * 返回最新n条文章
	 * <br />对应API：{@link http://api.haodai.com/article/get_article_dkgl_list article/get_article_dkgl_list}
	 * 
	 * @access public
	 * @param string $city 文章所属城市，默认北京
	 * @param int 	 $is_top 是否需要置顶文章
	 * @param int 	 $pg_num 返回结果的页码，默认为1
	 * @param int  	 $pg_size 单页返回的记录条数，默认为10
	 * @return array
	 */
	function get_article_dkgl_list( $city, $is_top, $pg_num = 1, $pg_size = 10)
	{
		$params = array();
		$params['is_top'] = $is_top;
		$params['city'] = $city;
		return $this->request_with_pager( 'article/get_article_dkgl_list', $pg_num, $pg_size, $params );
	}
	
	/**
	 * 获取贷款资讯文章
	 *
	 * 返回最新n条文章
	 * <br />对应API：{@link http://api.haodai.com/article/get_article_dkzx_list article/get_article_dkzx_list}
	 *
	 * @access public
	 * @param string $city 文章所属城市，默认北京
	 * @param int 	 $is_top 是否需要置顶文章
	 * @param int 	 $pg_num 返回结果的页码，默认为1
	 * @param int  	 $pg_size 单页返回的记录条数，默认为10
	 * @return array
	 */
	function get_article_dkzx_list( $city, $is_top, $pg_num = 1, $pg_size = 10)
	{
		$params = array();
		$params['is_top'] = $is_top;
		$params['city'] = $city;
		return $this->request_with_pager( 'article/get_article_dkzx_list', $pg_num, $pg_size, $params );
	}
	
	/**
	 * 获取常见问题文章
	 *
	 * 返回最新n条文章
	 * <br />对应API：{@link http://api.haodai.com/article/get_article_cjwt_list article/get_article_cjwt_list}
	 *
	 * @access public
	 * @param string $city 文章所属城市，默认北京
	 * @param int 	 $is_top 是否需要置顶文章
	 * @param int 	 $pg_num 返回结果的页码，默认为1
	 * @param int  	 $pg_size 单页返回的记录条数，默认为10
	 * @return array
	 */
	function get_article_cjwt_list( $city, $is_top, $pg_num = 1, $pg_size = 10)
	{
		$params = array();
		$params['is_top'] = $is_top;
		$params['city'] = $city;
		return $this->request_with_pager( 'article/get_article_cjwt_list', $pg_num, $pg_size, $params );
	}
	
	/**
	 * 获取经验分享文章
	 *
	 * 返回最新n条文章
	 * <br />对应API：{@link http://api.haodai.com/article/get_article_jyfx_list article/get_article_jyfx_list}
	 *
	 * @access public
	 * @param string $city 文章所属城市，默认北京
	 * @param int 	 $is_top 是否需要置顶文章
	 * @param int 	 $pg_num 返回结果的页码，默认为1
	 * @param int  	 $pg_size 单页返回的记录条数，默认为10
	 * @return array
	 */
	function get_article_jyfx_list( $city, $is_top, $pg_num = 1, $pg_size = 10)
	{
		$params = array();
		$params['is_top'] = $is_top;
		$params['city'] = $city;
		return $this->request_with_pager( 'article/get_article_jyfx_list', $pg_num, $pg_size, $params );
	}
	
	/**
	 * 获取文章详情
	 *
	 * 返回最新n条文章
	 * <br />对应API：{@link http://api.haodai.com/article/get_article_detail article/get_article_detail}
	 *
	 * @access public
	 * @param int 	 $id 文章id
	 * @return array
	 */
	function get_article_detail( $id)
	{
		$params = array();
		$params['id'] = $id;
		return $this->oauth->get( 'article/get_article_detail',$params );
	}
	
	/**
	 * 联盟帐号注册
	 *
	 * 对应API：{@link http://api.haodai.com/user/register_union_account user/register_union_account}
	 *
	 * @param array  $data 表单上传数组  [邮件:email, 电话:tel, 昵称:nickname, 密码：passwd, 姓名：realname, QQ号：qq, 网站链接：domain, 网站名：sitenamed]
	 * @return array
	 */
	function register_union_account($data=array())
	{
		$params = array();
		$params['email'] = $data['email'];
		$params['tel'] = $data['tel'];
		$params['nickname'] = $data['nickname'];
		$params['passwd'] = $data['passwd'];
		$params['realname'] = $data['realname'];
		$params['qq'] = $data['qq'];
		$params['domain'] = $data['domain'];
		$params['sitename'] = $data['sitename'];
		$res = $this->oauth->post('user/register_union_account', $params);				$this->oauth->union_ref = $res['hd_ref'];				return $res;
	}
	
	/**
	 * 好贷开放平台应用注册
	 *
	 * 对应API：{@link http://api.haodai.com/user/haodai_app_register user/haodai_app_register}
	 *
	 * @param array  $data 表单上传数组  [应用名:app_name, 应用站点地址:site_url, 应用简介:desc, 回调地址:callback_url]
	 * @return array
	 */
	function haodai_app_register($data=array())
	{
		$params = array();
		$params['app_name'] = $data['app_name'];
		$params['site_url'] = $data['site_url'];
		$params['desc'] = $data['desc'];
		$params['callback_url'] = $data['callback_url'];				return $this->oauth->post('user/haodai_app_register', $params);
	}
	// =========================================
	
	/**
	 * @ignore
	 */
	function haodai_check_AccessToken()
	{
		$params = array();
		return $this->oauth->get('common/check_AccessToken', $params);
	}
	
	/**
	 * @ignore
	 */
	protected function request_with_pager( $url, $pg_num = false, $pg_size = false, $params = array() )
	{
		if( $pg_num ) $params['pg_num'] = $pg_num;
		if( $pg_size ) $params['pg_size'] = $pg_size;

		return $this->oauth->get($url, $params );
	}

	/**
	 * @ignore
	 */
	protected function id_format(&$id) {
		if ( is_float($id) ) {
			$id = number_format($id, 0, '', '');
		} elseif ( is_string($id) ) {
			$id = trim($id);
		}
	}

}
